package com.design.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.design.config.CommonException;
import com.design.dao.entity.*;
import com.design.dao.mapper.*;
import com.design.model.*;
import com.design.service.ShippingRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ShippingRecordServiceImpl implements ShippingRecordService {
    @Autowired
    private ContainerMapper containerMapper;
    @Autowired
    private TemplateMapper templateMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ShippingRecordMapper shippingRecordMapper;
    @Autowired
    private ShippingRecordHistoryMapper shippingRecordHistoryMapper;

    @Override
    public void inputRecord(ShippingInputRequest request) {
        QueryWrapper<Container> containerQueryWrapper = new QueryWrapper<>();
        containerQueryWrapper.eq("container_num", request.getContainerNum());
        List<Container> containers = containerMapper.selectList(containerQueryWrapper);
        if (CollectionUtils.isEmpty(containers)) {
            throw new CommonException("集装箱编号或车板号对应信息不存在");
        }

        QueryWrapper<Template> templateQueryWrapper = new QueryWrapper<>();
        templateQueryWrapper.eq("template_num", request.getTemplateNum());
        List<Template> templates = templateMapper.selectList(templateQueryWrapper);
        if (CollectionUtils.isEmpty(templates)) {
            throw new CommonException("集装箱编号或车板号对应信息不存在");
        }

        UserInfo userInfo = userInfoMapper.selectById(request.getUserId());
        if (null == userInfo) {
            throw new CommonException("用户不存在");
        }
        userInfo.setStatus(false);
        userInfoMapper.updateById(userInfo);

        QueryWrapper<ShippingRecord> shippingRecordCheckQueryWrapper = new QueryWrapper<>();
        shippingRecordCheckQueryWrapper.eq("user_info_id", request.getUserId());
        shippingRecordCheckQueryWrapper.eq("state", 0);
        shippingRecordCheckQueryWrapper.eq("template_id", templates.get(0).getId());
        List<ShippingRecord> shippingRecordLists = shippingRecordMapper.selectList(shippingRecordCheckQueryWrapper);
        if (!CollectionUtils.isEmpty(shippingRecordLists)) {
            throw new CommonException("该车板已录入，请勿重复操作");
        }

        QueryWrapper<ShippingRecord> shippingRecordQueryWrapper = new QueryWrapper<>();
        shippingRecordQueryWrapper.orderByDesc("id");
        List<ShippingRecord> shippingRecords = shippingRecordMapper.selectList(shippingRecordQueryWrapper);
        int batchId = 1;
        if (!CollectionUtils.isEmpty(shippingRecords)) {
            if (shippingRecords.get(0).getState() == 0) {
                batchId = shippingRecords.get(0).getBatchId();
            } else {
                batchId = shippingRecords.get(0).getBatchId() + 1;
            }
        }

        ShippingRecord record = new ShippingRecord();
        record.setBatchId(batchId);
        record.setState((byte) 0);
        record.setContainerId((long) containers.get(0).getId());
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        record.setIsDelete((byte) 0);
        record.setTemplateId((long) templates.get(0).getId());
        record.setUserInfoId(userInfo.getId());
        shippingRecordMapper.insert(record);
    }

    @Override
    public List<String> queryCurrentRecord(Long userId) {
        QueryWrapper<ShippingRecord> shippingRecordQueryWrapper = new QueryWrapper<>();
        shippingRecordQueryWrapper.eq("user_info_id", userId);
        shippingRecordQueryWrapper.eq("state", 0);
        List<ShippingRecord> shippingRecords = shippingRecordMapper.selectList(shippingRecordQueryWrapper);
        if (CollectionUtils.isEmpty(shippingRecords)) {
            return new ArrayList<>();
        }
        List<Integer> templateIds = shippingRecords.stream().map(template -> {
            return template.getTemplateId().intValue();
        }).collect(Collectors.toList());
        QueryWrapper<Template> templateQueryWrapper = new QueryWrapper<>();
        templateQueryWrapper.in("id", templateIds);
        List<Template> templates = templateMapper.selectList(templateQueryWrapper);
        return templates.stream().map(Template::getTemplateNum).collect(Collectors.toList());
    }

    @Override
    public RecordInfoResponse queryCurrentRecordDetail(Long userId, String templateNum) {
        QueryWrapper<Template> templateQueryWrapper = new QueryWrapper<>();
        templateQueryWrapper.eq("template_num", templateNum);
        List<Template> templates = templateMapper.selectList(templateQueryWrapper);
        if (CollectionUtils.isEmpty(templates)) {
            throw new CommonException("车板编号对应车板信息不存在");
        }

        QueryWrapper<ShippingRecord> shippingRecordQueryWrapper = new QueryWrapper<>();
        shippingRecordQueryWrapper.eq("user_info_id", userId);
        shippingRecordQueryWrapper.eq("state", 0);
        shippingRecordQueryWrapper.eq("template_id", templates.get(0).getId());
        List<ShippingRecord> shippingRecords = shippingRecordMapper.selectList(shippingRecordQueryWrapper);
        if (CollectionUtils.isEmpty(shippingRecords)) {
            throw new CommonException("车板信息不存在");
        }
        ShippingRecord record = shippingRecords.get(0);
        RecordDTO dto = new RecordDTO();
        dto.setFrontRear(record.getFrontRear());
        dto.setLeftRight(record.getLeftRight());
        dto.setTotalWeight(record.getTotalWeight());
        record.setHistory(JSONObject.toJSONString(dto));
        shippingRecordMapper.updateById(record);

        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (null == userInfo) {
            throw new CommonException("用户不存在");
        }
        return getRecordInfoResponse(record, userInfo);
    }

    private RecordInfoResponse getRecordInfoResponse(ShippingRecord record, UserInfo userInfo) {
        RecordInfoResponse recordInfoResponse = new RecordInfoResponse();
        RecordFrontDetailsDTO frontDetailsDTO = new RecordFrontDetailsDTO();
        RecordLeftDetailsDTO leftDetailsDTO = new RecordLeftDetailsDTO();
        RecordTotalDetailsDTO totalDetailsDTO = new RecordTotalDetailsDTO();


        recordInfoResponse.setWeight1(record.getWeight1());
        recordInfoResponse.setWeight2(record.getWeight2());
        recordInfoResponse.setWeight3(record.getWeight3());
        recordInfoResponse.setWeight4(record.getWeight4());
        recordInfoResponse.setLink1(record.getLink1());
        recordInfoResponse.setLink2(record.getLink2());
        recordInfoResponse.setLink3(record.getLink3());
        recordInfoResponse.setLink4(record.getLink4());

        recordInfoResponse.setId(record.getId());
        recordInfoResponse.setBatchId(record.getBatchId());
        recordInfoResponse.setUpdateTime(record.getUpdateTime());
        recordInfoResponse.setDeviceNo(record.getDeviceNo());
        recordInfoResponse.setRealFrontRear(record.getFrontRear());
        recordInfoResponse.setRealLeftRight(record.getLeftRight());
        recordInfoResponse.setRealTotalWeight(record.getTotalWeight());
        if (userInfo.isStatus() && !StringUtils.isEmpty(record.getHistory())) {
            RecordDTO dto = JSONObject.parseObject(record.getHistory(), RecordDTO.class);
            recordInfoResponse.setRealFrontRear(dto.getFrontRear());


            recordInfoResponse.setRealLeftRight(dto.getLeftRight());

            recordInfoResponse.setRealTotalWeight(dto.getTotalWeight());
        }

        recordInfoResponse.setCarNum(userInfo.getCarNum());
        recordInfoResponse.setCarModel(userInfo.getModel());
        recordInfoResponse.setCarProducer(userInfo.getProducer());
        recordInfoResponse.setCarCompany(userInfo.getCompany());


        Container container = containerMapper.selectById(record.getContainerId());
        if (null != container) {
            recordInfoResponse.setContainerNum(container.getContainerNum());
            recordInfoResponse.setContainerModel(container.getModel());
            recordInfoResponse.setContainerProducer(container.getProducer());
            recordInfoResponse.setContainerSize(container.getSize());
            recordInfoResponse.setTotalWeight(container.getTotalWeight());
            recordInfoResponse.setFrontRear(container.getFrontRear());
            recordInfoResponse.setLeftRight(container.getLeftRight());
        }

        Template template = templateMapper.selectById(record.getTemplateId());
        if (null != template) {
            recordInfoResponse.setTemplateCompany(template.getCompany());
            recordInfoResponse.setTemplateNum(template.getTemplateNum());
            recordInfoResponse.setTemplateProducer(template.getProducer());
        }

        frontDetailsDTO.setFrontRear(recordInfoResponse.getFrontRear());
        frontDetailsDTO.setRealFrontRear(recordInfoResponse.getRealFrontRear());

        leftDetailsDTO.setLeftRight(recordInfoResponse.getLeftRight());
        leftDetailsDTO.setRealLeftRight(recordInfoResponse.getRealLeftRight());

        totalDetailsDTO.setTotalWeight(recordInfoResponse.getTotalWeight());
        totalDetailsDTO.setRealTotalWeight(recordInfoResponse.getRealTotalWeight());

        QueryWrapper<ShippingRecordHistory> shippingRecordHistoryQueryWrapper = new QueryWrapper<>();
        shippingRecordHistoryQueryWrapper.eq("shipping_record_id", record.getId());
        shippingRecordHistoryQueryWrapper.orderByDesc("id");
        Page<ShippingRecordHistory> recordHistories = shippingRecordHistoryMapper.selectPage(new Page<>(1, 5),shippingRecordHistoryQueryWrapper);
        List<BigDecimal> frontDetailsList = new ArrayList<>();
        List<BigDecimal>  leftDetailsList = new ArrayList<>();
        List<BigDecimal>  totalDetailsList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(recordHistories.getRecords())){
            recordHistories.getRecords().forEach(item ->{
                frontDetailsList.add(item.getFrontRear());
                leftDetailsList.add(item.getLeftRight());
                totalDetailsList.add(item.getTotalWeight());
            });
        }
        frontDetailsDTO.setHistory(frontDetailsList);
        leftDetailsDTO.setHistory(leftDetailsList);
        totalDetailsDTO.setHistory(totalDetailsList);
        recordInfoResponse.setFrontDetailsDTO(frontDetailsDTO);
        recordInfoResponse.setLeftDetailsDTO(leftDetailsDTO);
        recordInfoResponse.setTotalDetailsDTO(totalDetailsDTO);
        return recordInfoResponse;
    }

    @Override
    public void deleteRecord(Integer id) {
        shippingRecordMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void finish(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (null == userInfo) {
            throw new CommonException("用户不存在");
        }
        userInfo.setStatus(true);
        userInfoMapper.updateById(userInfo);

        QueryWrapper<ShippingRecord> shippingRecordQueryWrapper = new QueryWrapper<>();
        shippingRecordQueryWrapper.eq("user_info_id", userId);
        shippingRecordQueryWrapper.eq("state", 0);
        ShippingRecord shippingRecord = new ShippingRecord();
        shippingRecord.setState((byte) 1);
        shippingRecordMapper.update(shippingRecord, shippingRecordQueryWrapper);
    }

    @Override
    public PageResult<UserRecordResponse> queryUserRecords(Long userId, Integer status, Integer batchId, Integer pageNum, Integer pageSize) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (null == userInfo) {
            throw new CommonException("用户不存在");
        }
        UserRecordResponse recordResponse = new UserRecordResponse();
        recordResponse.setGender(userInfo.getGender());
        recordResponse.setCarNum(userInfo.getCarNum());
        recordResponse.setUserName(userInfo.getUserName());
        recordResponse.setPhone(userInfo.getPhone());
        recordResponse.setIdNum(userInfo.getIdNum());

        List<RecordInfoResponse> list = new ArrayList<>();
        recordResponse.setRecordInfoResponses(list);
        QueryWrapper<ShippingRecord> shippingRecordQueryWrapper = new QueryWrapper<>();
        shippingRecordQueryWrapper.eq("user_info_id", userId);
        if(batchId != null){
            shippingRecordQueryWrapper.eq("batch_id", batchId);
        }
        if (status == 0) {
            shippingRecordQueryWrapper.eq("state", 0);
        } else {
            shippingRecordQueryWrapper.eq("state", 1);
        }
        shippingRecordQueryWrapper.orderByDesc("batch_id");
        Page<ShippingRecord> page = shippingRecordMapper.selectPage(new Page<>(pageNum, pageSize), shippingRecordQueryWrapper);
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            page.getRecords().forEach(shippingRecord -> {
                list.add(getRecordInfoResponse(shippingRecord, userInfo));
            });
        }
        return new PageResult<>(recordResponse, page.getTotal());
    }


    @Override
    public void report(ReportRequest request) {

        QueryWrapper<Container> containerQueryWrapper = new QueryWrapper<>();
        containerQueryWrapper.eq("container_num", request.getContainerNum());
        List<Container> containers = containerMapper.selectList(containerQueryWrapper);
        if (CollectionUtils.isEmpty(containers)) {
            throw new CommonException("集装箱编号对应集装箱信息不存在");
        }
        
        Container container = containers.get(0);
        QueryWrapper<ShippingRecord> shippingRecordQueryWrapper = new QueryWrapper<>();
        shippingRecordQueryWrapper.eq("container_id", container.getId());
        shippingRecordQueryWrapper.eq("state", 0);

        List<ShippingRecord> recordList = shippingRecordMapper.selectList(shippingRecordQueryWrapper);
        if(CollectionUtils.isEmpty(recordList)){
            throw new CommonException("运输未开始");
        }
        
        ShippingRecord historyRecord = recordList.get(0);
        ShippingRecordHistory history = new ShippingRecordHistory();
        history.setShippingRecordId(historyRecord.getId());
        history.setFrontRear(historyRecord.getFrontRear());
        history.setLeftRight(historyRecord.getLeftRight());
        history.setTotalWeight(historyRecord.getTotalWeight());
        history.setWeight1(historyRecord.getWeight1());
        history.setWeight2(historyRecord.getWeight2());
        history.setWeight3(historyRecord.getWeight3());
        history.setWeight4(historyRecord.getWeight4());
        history.setLink1(historyRecord.getLink1());
        history.setLink2(historyRecord.getLink2());
        history.setLink3(historyRecord.getLink3());
        history.setLink4(historyRecord.getLink4());
        history.setUpdateTime(new Date());
        history.setCreateTime(new Date());
        history.setIsDelete((byte)0);
        shippingRecordHistoryMapper.insert(history);

        ShippingRecord shippingRecord = new ShippingRecord();
        shippingRecord.setFrontRear(request.getFrontRear());
        shippingRecord.setLeftRight(request.getLeftRight());
        shippingRecord.setTotalWeight(request.getTotalWeight());
        shippingRecord.setDeviceNo(request.getDeviceNo());
        shippingRecord.setUpdateTime(new Date());
        shippingRecord.setWeight1(request.getWeight1());
        shippingRecord.setWeight2(request.getWeight2());
        shippingRecord.setWeight3(request.getWeight3());
        shippingRecord.setWeight4(request.getWeight4());
        shippingRecord.setLink1(request.getLink1());
        shippingRecord.setLink2(request.getLink2());
        shippingRecord.setLink3(request.getLink3());
        shippingRecord.setLink4(request.getLink4());
        shippingRecordMapper.update(shippingRecord, shippingRecordQueryWrapper);
    }

    @Override
    public void trigger() {
        RestTemplate template = new RestTemplate();
        ResponseEntity<String> result = template.getForEntity("http://39.101.165.116:9999/getLastRec ", String.class);
        log.info("触发结果：{}", JSONObject.toJSONString(result));
    }
}
